package com.shortchainsystem.gateway.filter;

import com.shortchainsystem.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * 基于全局过滤器实现统一登录验证
 */
@Slf4j
@Component
public class AuthorizeFilter implements Ordered,GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        // 检查路径是否以 /user 或 /link 开头
        if (!path.startsWith("/user") && !path.startsWith("/link")) {
            // 修改路径，添加 /link 前缀
            String newPath = "/link" + path;
            ServerHttpRequest modifiedRequest = request.mutate().path(newPath).build();
            return chain.filter(exchange.mutate().request(modifiedRequest).build());
        }

        // 其余路径需要登录验证
        if(!path.startsWith("/user/login") && !path.startsWith("/user/register")){
            String token = String.valueOf(request.getHeaders().get("token").get(0));
            if(token==null || token.equals(""))
            return exchange.getResponse().setComplete();
        }
        // 直接放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
